package org.exam.blog.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.exam.blog.domain.Article;
import org.exam.blog.mapper.ArticleMapper;
import org.exam.blog.query.MessageQuery;
import org.exam.blog.service.IArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class ArticleServiceImpl implements IArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    @Transactional
    public void add(Article article) {
        articleMapper.add(article);
        article.setUpdateTime(new Date());
        //添加
        mongoTemplate.save(article);

    }

    @Override
    @Transactional
    public void delete(Long id) {
        articleMapper.delete(id);
        //条件删除
        Query query = new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query, Article.class);
    }

    @Override
    public Article get(Long id) {
        List<Article> all = articleMapper.getAll();
        return articleMapper.get(id);
    }

    @Override
    public List<Article> getAll() {
        return articleMapper.getAll();
    }

    @Override
    public List<Article> getAll1() {
        return articleMapper.getAll1();
    }

    @Override
    @Transactional
    public void update(Article article) {
        article.setUpdateTime(new Date());
        articleMapper.update(article);
        //MongoDB修改
    }

    @Override
    public void patchDelete(Long[] ids) {
        articleMapper.patchDelete(ids);
    }

    @Override
    public PageInfo<Article> queryPage(MessageQuery messageQuery) {
        PageHelper.startPage(messageQuery.getCurrentPage(), messageQuery.getPageSize());
        List<Article> data = articleMapper.queryPage(messageQuery);
        return new PageInfo<>(data);
    }

    @Override
    public List<Article> dependenceArticles(Long id) {
        return articleMapper.dependenceArticles(id);
    }

}
